<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Model;
use Think\Model;

class AuthGroupModel extends CommonModel
{
    
    // 管理员用户组类型标识
    const TYPE_ADMIN = 1;

    const MEMBER = 'member';

    const UCENTER_MEMBER = 'ucenter_member';
    
    // 关系表表名
    const AUTH_GROUP_ACCESS = 'auth_group_access';
    
    // 动态权限扩展信息表
    const AUTH_EXTEND = 'auth_extend';
    
    // 用户组表名
    const AUTH_GROUP = 'auth_group';
    
    // 分类权限标识
    const AUTH_EXTEND_CATEGORY_TYPE = 1;
    
    // 分类权限标识
    const AUTH_EXTEND_MODEL_TYPE = 2;
    
    // 大厦管理权限
    const AUTH_EXTEND_BUILDING_TYPE = 9;

    /**
     * 把用户添加到用户组,支持批量添加用户到用户组
     */
    public function addToGroup ($uid, $gid)
    {
        $uid = is_array($uid) ? implode(',', $uid) : trim($uid, ',');
        $gid = is_array($gid) ? $gid : explode(',', trim($gid, ','));
        
        $Access = M(self::AUTH_GROUP_ACCESS);
        if (isset($_REQUEST['batch']))
        {
            // 为单个用户批量添加用户组时,先删除旧数据
            $del = $Access->where(array(
                    'uid' => array(
                            'in',
                            $uid
                    )
            ))->delete();
        }
        
        $uid_arr = explode(',', $uid);
        $uid_arr = array_diff($uid_arr, array(
                C('USER_ADMINISTRATOR')
        ));
        $add = array();
        if ($del !== false)
        {
            foreach ($uid_arr as $u)
            {
                // 判断用户id是否合法
                if (M('Member')->getFieldByUid($u, 'uid') == false)
                {
                    $this->error = "编号为{$u}的用户不存在！";
                    return false;
                }
                foreach ($gid as $g)
                {
                    if (is_numeric($u) && is_numeric($g))
                    {
                        $add[] = array(
                                'group_id' => $g,
                                'uid' => $u
                        );
                    }
                }
            }
            $Access->addAll($add);
        }
        if ($Access->getDbError())
        {
            if (count($uid_arr) == 1 && count($gid) == 1)
            {
                // 单个添加时定制错误提示
                $this->error = "不能重复添加";
            }
            return false;
        }
        else
        {
            return true;
        }
    }

    /**
     * 返回用户所属用户组信息
     */
    static public function getUserGroup ($uid)
    {
        static $groups = array();
        if (isset($groups[$uid]))
            return $groups[$uid];
        $prefix = C('DB_PREFIX');
        $user_groups = M()->field('uid,group_id,title,description,rules')->table($prefix . self::AUTH_GROUP_ACCESS . ' a')->join($prefix . self::AUTH_GROUP . " g on a.group_id=g.id")->where("a.uid='$uid' and g.status='1'")->select();
        $groups[$uid] = $user_groups ? $user_groups : array();
        return $groups[$uid];
    }

    /**
     * 返回用户拥有管理权限的扩展数据id列表
     */
    static public function getAuthExtend ($uid, $type, $session)
    {
        if (! $type)
        {
            return false;
        }
        $session = false;
        if ($session)
        {
            $result = session($session);
        }
        if ($uid == UID && ! empty($result))
        {
            return $result;
        }
        $prefix = C('DB_PREFIX');
        $result = M()->table($prefix . self::AUTH_GROUP_ACCESS . ' g')->join($prefix . self::AUTH_EXTEND . ' c on g.group_id=c.group_id')->where("g.uid='$uid' and c.type='$type' and !isnull(extend_id)")->getfield('extend_id', true);
        if ($uid == UID && $session)
        {
            session($session, $result);
        }
        return $result;
    }

    /**
     * 返回用户拥有管理权限的分类id列表
     */
    static public function getAuthCategories ($uid)
    {
        return self::getAuthExtend($uid, self::AUTH_EXTEND_CATEGORY_TYPE, 'AUTH_CATEGORY');
    }

    /**
     * 获取用户组授权的扩展信息数据
     */
    static public function getExtendOfGroup ($gid, $type)
    {
        if (! is_numeric($type))
        {
            return false;
        }
        return M(self::AUTH_EXTEND)->where(array(
                'group_id' => $gid,
                'type' => $type
        ))->getfield('extend_id', true);
    }

    /**
     * 获取用户组授权的分类id列表
     */
    static public function getCategoryOfGroup ($gid)
    {
        return self::getExtendOfGroup($gid, self::AUTH_EXTEND_CATEGORY_TYPE);
    }

    /**
     * 批量设置用户组可管理的扩展权限数据
     */
    static public function addToExtend ($gid, $cid, $type)
    {
        $gid = is_array($gid) ? implode(',', $gid) : trim($gid, ',');
        $cid = is_array($cid) ? $cid : explode(',', trim($cid, ','));
        
        $Access = M(self::AUTH_EXTEND);
        $del = $Access->where(array(
                'group_id' => array(
                        'in',
                        $gid
                ),
                'type' => $type
        ))->delete();
        
        $add = array();
        if ($del !== false)
        {
            foreach (explode(',', $gid) as $g)
                foreach ($cid as $c)
                    is_numeric($g) and is_numeric($c) and $add[] = array(
                            'group_id' => $g,
                            'extend_id' => $c,
                            'type' => $type
                    );
            $Access->addAll($add);
        }
        return ! $Access->getDbError();
    }
    
    // 保存权限设置
    public function updateAccess ($data, $where)
    {
        sort($data['rules']);
        $saveData = [
                'rules' => implode(',', array_unique($data['rules'])),
                'module' => 'admin',
                'type' => self::TYPE_ADMIN
        ];
        return $this->where([
                'id' => $where['auth_group.id']
        ])->save($saveData) !== false;
    }
    
    // 保存分类设置
    public function updateCategory ($data, $where)
    {
        return self::addToExtend($where['auth_group.id'], $data['cid'], self::AUTH_EXTEND_CATEGORY_TYPE);
    }
}

